package com.mind.customer.template;

// JsonPathResolver.java

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;

public class JsonPathResolver {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static List<String> resolveValue(JsonNode rootNode, String path) {
        List<String> results = new ArrayList<>();

        String[] parts = path.split("\\.");
        JsonNode currentNode = rootNode;

        for (int i = 0; i < parts.length; i++) {
            String part = parts[i];

            if (currentNode == null || currentNode.isNull()) {
                results.add("");
                break;
            }

            if (currentNode.isArray()) {
                // 处理数组路径
                for (JsonNode arrayElement : currentNode) {
                    JsonNode nestedNode = arrayElement;
                    String arrayPart = null;
                    for (int j = i; j < parts.length; j++) {
                        if (nestedNode == null) {
                            break;
                        }
                        if (nestedNode.get(parts[j]) == null) {
                            break;
                        } else {
                            nestedNode = nestedNode.get(parts[j]);
                        }
                        // 判断是否是数组
                        if (nestedNode == null) {
                            break;
                        }
                        if (nestedNode.isArray()) {
                            arrayPart = parts[j + 1];
                            break;
                        }
                    }
                    if (nestedNode.isArray()) {
                        for (JsonNode node : nestedNode) {
                            JsonNode nestedNode2 = node;
                            nestedNode2 = nestedNode2.get(arrayPart);

                            results.add(formatValue(nestedNode2));
                        }
                    } else {
                        results.add(formatValue(nestedNode));
                    }
                }
                return results;
            } else {
                currentNode = currentNode.get(part);
            }
        }

        if (results.isEmpty() && currentNode != null) {
            results.add(formatValue(currentNode));
        }
        return results;
    }

    private static String formatValue(JsonNode node) {
        if (node == null) return "";
        if (node.isTextual()) return node.asText();
        if (node.isNumber()) return String.valueOf(node.asDouble());
        if (node.isBoolean()) return String.valueOf(node.asBoolean());
        if (node.isNull()) return "";
        return node.toString();
    }
}
